import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'

import { setMessage } from '_redux/actions/message'
import { findReasonById, findCriosAndVarietiesList, findSoilList } from 'utils/Api'

import { setFieldMessage, startFieldMessage } from '_redux/actions/fieldMessage'

import Abstract from './Abstract'
class FiledInfo extends Component {
  constructor(props) {
    super(props)
    const feature  = props.feature
    this.state = {
      isNew: feature.get('status'),
      message: {},
      flag: false
    }
  }
  handelefindSoilList() {
    return findSoilList()
      .then(({ msg, result }) => {
        if (msg === '200') {
          this.props.setMessage({
            soilTypes: result
          })
        }
      })
  }
  handleCriosAndVarieties() {
    return findCriosAndVarietiesList()
      .then(({ msg, result }) => {
        if (msg === '200') {
          this.props.setMessage({
            criosAndVarietiesList: result
          })
        }
      })

  }
  componentDidMount() {
    const {feature} = this.props
    this.handelefindSoilList()
      .then(e => this.handleCriosAndVarieties())
      .then(e => {
        if ('0' === this.state.isNew) {
          const id = feature.getId().replace('tb_farmland.', '')
          findReasonById({
            farmLandId: id,
            isNew: 0
          })
            .then(({ msg, result }) => {
              if (msg === '200') {
                this.setState({
                  message: result,
                  flag: true
                })
                this.props.setFieldMessage(result)
              }
            })
        }
      }) 
  }
  start = () => {
    this.props.startFieldMessage(true)
  }
  render() {
    return this.state.isNew === '1' ? <div className='filed-info'>
      <div>你目前还没有填写田地信息</div>
      <button className='content-btn' onClick={this.start}>开始填写</button>
    </div> : 
      this.state.flag && <Abstract feature={this.props.feature} fieldMessage={this.state.message}/>
  }
}
FiledInfo.propTypes = {
  startFieldMessage: PropTypes.func,
  feature: PropTypes.object,
  setMessage: PropTypes.func,
  setFieldMessage: PropTypes.func,
  fieldMessage: PropTypes.object
    
}

export default connect(({ fieldMessage }) => ({
  fieldMessage
}), dispatch => ({
  startFieldMessage: start => dispatch(startFieldMessage(start)),
  setFieldMessage: start => dispatch(setFieldMessage(start)),
  setMessage: start => dispatch(setMessage(start)),
}))(FiledInfo)